import base64
import re


def convert_to_numbers(s):
    """
    将选项字母等转为数字，如 A->1, B->2，多个字母用逗号分隔
    """
    if not s:
        return ""

    s = re.sub(r"[，、\s]+", ",", s.strip())

    if all(c.isdigit() or c == "," for c in s):
        if "," not in s:
            return ",".join(list(s))
        else:
            return s

    letters = re.split(r"[，,、\s]+", s.strip())
    result = []
    for item in letters:
        for c in item:
            if c.isalpha():
                result.append(str(ord(c.upper()) - ord('A') + 1))
            elif c.isdigit():
                result.append(c)
    return ",".join(result)


def is_tf(tf_str: str) -> bool:
    """
    判断是否为判断题（即同时包含“正确”和“错误”，且距离不超过3个字符）

    参数:
        tf_str (str): 待判断的原始字符串

    返回:
        bool: 满足判断题条件返回 True，否则返回 False
    """
    if not isinstance(tf_str, str) or not tf_str.strip():
        return False

    tf_str = tf_str.strip()

    # 正则方式匹配“正确”与“错误”，中间最多 3 个字符（含换行空格等）
    pattern = r'(正确.{0,3}错误|错误.{0,3}正确)'
    return bool(re.search(pattern, tf_str))


def fix_base64_padding(s):
    """给base64字符串补齐等号"""
    if not s:
        return s
    return s + '=' * ((4 - len(s) % 4) % 4)


def is_valid_base64(s):
    """用正则和解码判断base64是否合法"""
    if not s:
        return False
    # 先用正则粗略匹配
    base64_pattern = r'^[A-Za-z0-9+/]+={0,2}$'
    if not re.match(base64_pattern, s):
        return False
    # 再尝试解码
    try:
        base64.b64decode(s)
        return True
    except Exception:
        return False
